package model;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import view.Vista;


public class Processamento extends Thread{

	private String clientSentence;
	private Socket connectionSocket;
	private BufferedReader inFromClient;
	private DataOutputStream outToClient;
	private Conexoes conexoes;
	private Vista vista;

	public Processamento(Socket socket,Conexoes conexoes,Vista vista){
		this.vista=vista;
		try{
			this.connectionSocket=socket;
			this.inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
		}catch(IOException ioe){}
		this.conexoes=conexoes;
		this.conexoes.addConexao(this.connectionSocket);
	}
	
	public void run(){
		while(true){
			try{
				this.clientSentence=inFromClient.readLine();
				this.vista.escreveNaTela("servidor recebeu mensagem de "+this.connectionSocket.getInetAddress().toString().substring(1));
				if(clientSentence!=null){
					for(int i=0;i<conexoes.numeroConexoes();i++){
						this.outToClient=new DataOutputStream(conexoes.getConexao(i).getOutputStream());
						this.outToClient.writeBytes(this.clientSentence+'\n');
						this.vista.escreveNaTela("servidor enviou mensagem para "+this.conexoes.getConexao(i).getInetAddress().toString().substring(1));
					}
				}
			}catch(IOException ioe ){}
		}
	}
}
